package com.example.canal.redis.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @author lemon
 * @email lemon
 * @desc: 工具类
 */
public class JsonUtils {




    private JsonUtils() {
    }


    /**
     * The Constant MAPPER.
     */
    public final static ObjectMapper MAPPER;

    static {
        MAPPER = new ObjectMapper();
        // 遇到未知field不报错
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        MAPPER.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        //反序列化的时候如果多了其它属性，不抛出异常
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //如果是空对象的时候，不抛异常
        MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // 接受单个字符的值反序列化为数组
        MAPPER.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        // 没有匹配的属性名称时不作失败处理
        MAPPER.configure(MapperFeature.AUTO_DETECT_FIELDS, true);
        //取消时间的转换格式，默认是时间戳，同时需设置时间格式
        MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }


    private static Logger LOGGER = LoggerFactory.getLogger(JsonUtils.class);

    /**
     * 序列化
     *
     * @param o the o
     * @return the string
     */
    public static String objectToString(Object o) {
        try {
            return MAPPER.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            LOGGER.error("序列话错误:",e);
            throw new RuntimeException("序列化异常:",e);
        }
    }


    public static <T> T parseObject(Object o, TypeReference<T> type) {
        try {
            return o != null ? MAPPER.readValue(objectToString(o), type) : null;
        } catch (IOException var3) {
            LOGGER.error("object parse type error", var3);
            throw new RuntimeException("反序列化异常", var3);
        }
    }

    public static <T> T parseObject(String s, TypeReference<T> type) {
        try {
            return MAPPER.readValue(s, type);
        } catch (IOException var3) {
            LOGGER.error("string parse object error ", var3);
            throw new RuntimeException("反序列化异常", var3);
        }
    }




}
